const fs = require('fs')
const path = require('path')

const fileName = path.join(__dirname, 'b1.tlv')
const typeUseByte = 4 // 类型占用字节
const lengthUseByte = 4 // 长度占用字节
let readedByte = 0 // 已读已发送字节长度

const WebSocket = require('ws')
const wss = new WebSocket.Server({
//   host: 'localhost',
  host: '192.168.0.133',
  port: 9999,
//   host: '192.168.0.187',
//   port: 7681,
  // perMessageDeflate: {
  //   serverMaxWindowBits: 20
  // }
})

let ws1
console.log('socket已打开')
wss.on('connection', function (ws) {
//   console.log(ws) 一大堆
  ws1 = ws
  ws.on('message', function(message) {
    console.log('server: 收到')
    fs.open(fileName, 'r', function(err, fd) {
      console.log('文件已打开')
      const array = []
      if (err) {
        throw err
      }
      fs.readFile(fileName, function(err, data) {
        console.log(data)
        console.log('文件已读取')
        if (err) {
          throw err
        }
        while (readedByte < data.length) {
          const typeBuffer = data.slice(readedByte, readedByte + typeUseByte)
          // typeBuffer = typeBuffer.reverse()
          const type = typeBuffer // hex2int(typeBuffer.toString('hex'))

          readedByte += typeUseByte
          let lengthBuffer = data.slice(readedByte, readedByte + lengthUseByte)
          // console.log(lengthBuffer)
          // console.log(lengthBuffer)
          const length = hex2int(lengthBuffer.reverse().toString('hex'))
          lengthBuffer = lengthBuffer.reverse()

          readedByte += lengthUseByte

          const val = data.subarray(readedByte - 8, readedByte + length)
          readedByte += length
          // console.log(val)
          // wss.clients.forEach(client => {
          //   if (client.readyState === WebSocket.OPEN) {
          //     client.send(val)
          //   }
          // })
          ws.send(val)
          array.push({
            type,
            length,
            val
          })
        //   console.log(array)
        }
        console.log('文件已发送')
        fs.close(fd, function() {
          readedByte = 0
          console.log('文件关闭')
        })
      })
    })
  })
  // ws.send('server: hello,client')
})

function hex2int(i) {
  let two = parseInt(i, 16).toString(2)
  const bitNum = i.length * 4
  if (two.length < bitNum) {
    while (two.length < bitNum) {
      two = '0' + two
    }
  }

  if (two.substring(0, 1) == '0') {
    two = parseInt(two, 2)
    return two
  } else {
    let two_unsign = ''
    two = parseInt(two, 2) - 1
    two = two.toString(2)

    two_unsign = two.substring(1, bitNum)
    two_unsign = two_unsign.replace(/0/g, 'z')

    two_unsign = two_unsign.replace(/1/g, '0')

    two_unsign = two_unsign.replace(/z/g, '1')
    console.log(parseInt(-two_unsign, 10))
    two = parseInt(-two_unsign, 2)

    return two
  }
}
